package com.jifeng.api.utils;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jifeng.api.crud.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtils {
    /**
     * 获取token
     *
     * @param account
     * @param password
     * @return
     */
    public static String getToken(String account, String password) {
        try {//
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("client_id", "client");
            paramMap.put("client_secret", "secret");
            paramMap.put("grant_type", "password");
            paramMap.put("password", password);
            paramMap.put("username", account);

            String jsonStr = HttpUtil.post("https://server.youbeihu.top:9000/oauth/token", paramMap);
            cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
            Object data = jsonObject.get("data");
            String string = data.toString();
            cn.hutool.json.JSONObject jsonObject2 = JSONUtil.parseObj(string);
            return jsonObject2.get("access_token").toString();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "获取token", e.getMessage());
            return "";
        }
    }

    /**
     * 从token获得户主id
     *
     * @param request
     * @return
     */
    public static Map<String,Object> getUserIdByToken(HttpServletRequest request) {
        String uri = "https://server.youbeihu.top:9000/oauth/check_token";
        try {
            String authorization = request.getHeader("Authorization");
            if (StringUtils.isEmpty(authorization)) {
                log.warn("path：{}，errMsg：{}", request.getRequestURI(), "token为空");
                return null;
            }
            int i = authorization.indexOf(" ");
            String token = authorization.substring(i + 1);
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                // 创建一个提交数据的容器
                List<BasicNameValuePair> parames = new ArrayList<>();
                parames.add(new BasicNameValuePair("token", token));

                HttpPost httpPost = new HttpPost(uri);
                httpPost.setEntity(new UrlEncodedFormEntity(parames, "UTF-8"));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                Map map = JSON.parseObject(result, Map.class);
                String info = JSON.toJSONString(map.get("info"));
                Map map2 = JSON.parseObject(info, Map.class);
                return map2;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    // 设备租赁
    public static boolean rentDevice(String imei, String oper, String phoneNum, String number) {
        try {
            String uri = "http://101.200.220.238:8081/bms/rentDevice";
            Map<String, Object> reqParams = new HashMap<>();
            reqParams.put("imei", imei);
            reqParams.put("oper", oper);
            reqParams.put("phoneNum", phoneNum);
            reqParams.put("number", number);
            String response = HttpUtil.get(uri, reqParams);
//            log.info("rentDevice-发送给下位机的数据：imei：{}，oper：{}，phoneNum：{}，number：{}", imei,oper,phoneNum,number);
//            log.info("rentDevice-下位机响应：{}", response);
            Map<String, Object> data = JSON.parseObject(response);
            return data.get("code").toString().equals("200");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", "发送请求进行设备租赁", e.getMessage());
            return false;
        }
    }

    // 设备归还
    public static boolean rentBackDevice(String imei, String oper) {
        try {
            String uri = "http://101.200.220.238:8081/bms/rentbackDevice";
            Map<String, Object> reqParams = new HashMap<>();
            reqParams.put("imei", imei);
            reqParams.put("oper", oper);
            String response = HttpUtil.get(uri, reqParams);
//            log.info("rentBackDevice-发送给下位机的数据：imei：{}，oper：{}", imei,oper);
//            log.info("rentBackDevice-下位机响应：{}", response);
            Map<String, Object> data = JSON.parseObject(response);
            return data.get("code").toString().equals("200");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", "设备归还", e.getMessage());
            return false;
        }
    }

    // 仓门控制
    public static boolean optCabitControl(String imei, String num) {
        String uri = "http://101.200.220.238:8081/bms/optCabitControlNew?imei=" + imei + "&num=" + num;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(uri);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
                return true;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", "发送请求进行仓门控制", e.getMessage());
            return false;
        }
    }

    // 仓门禁用状态控制
    public static boolean optCabitStauts(String imei, String status) {
        String uri = "http://101.200.220.238:8081/bms/optCabitStauts?imei=" + imei + "&status=" + status;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(uri);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
                return true;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", "发送请求进行仓门禁用状态控制", e.getMessage());
            return false;
        }
    }

    // 修改终端信息
    public static void updateTerminal(TerminalEntity terminalEntity) {
        /**
         * Post发送json数据
         */
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                // 101.200.167.174
                HttpPost httpPost = new HttpPost("http://101.200.167.174:9000/crud/terminal/update");
                httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
                httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(terminalEntity),
                        ContentType.create("text/json", "UTF-8")));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 修改设备信息
    public static void updateDevice(DeviceinfoEntity deviceinfoEntity) {
        /**
         * Post发送json数据
         */
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                // 101.200.167.174
                HttpPost httpPost = new HttpPost("http://101.200.167.174:9000/crud/deviceinfo/myUpdate");
                httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
                httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(deviceinfoEntity),
                        ContentType.create("text/json", "UTF-8")));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 修改心脏信息
    public static void updateHeart(HeartEntity heartEntity) {
        /**
         * Post发送json数据
         */
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                // 101.200.167.174
                HttpPost httpPost = new HttpPost("http://101.200.167.174:9000/crud/heart/myUpdate");
                httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
                httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(heartEntity),
                        ContentType.create("text/json", "UTF-8")));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 修改租赁信息
    public static void updateRent(RentEntity rentEntity) {
        /**
         * Post发送json数据
         */
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                // 101.200.167.174
                HttpPost httpPost = new HttpPost("http://101.200.167.174:9000/crud/rent/update");
                httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
                httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(rentEntity),
                        ContentType.create("text/json", "UTF-8")));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改订单信息
     */
    public static void updateOrder(OrderEntity orderEntity) {
        try {
            String url = "http://101.200.167.174:9000/crud/order/update";
            String jsonString = JSONObject.toJSONString(orderEntity);
            //链式构建请求
            String returnData = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json")//头信息，多个头信息多次调用此方法即可
                    .body(jsonString)//表单内容
                    .execute().body();
            System.out.println(returnData);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", "修改订单信息", e.getMessage());
        }
    }

    /**
     * 修改费用配置信息
     */
    public static void updateFeeConfig(FeeConfigEntity feeConfigEntity) {
        try {
            String url = "http://101.200.167.174:9000/crud/fee/update";
            String jsonString = JSONObject.toJSONString(feeConfigEntity);
            //链式构建请求
            String returnData = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json")//头信息，多个头信息多次调用此方法即可
                    .body(jsonString)//表单内容
                    .execute().body();
            System.out.println(returnData);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", "修改费用配置信息", e.getMessage());
        }
    }
}
